package com.buba.shirodemo.config;

import com.buba.shirodemo.pojo.User;
import com.buba.shirodemo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;


//自定义的UserRealm
public class UserRealm extends AuthorizingRealm  {
    @Autowired
    private UserService userService;
    //shouquan
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User principal = (User) subject.getPrincipal();
        info.addStringPermission(principal.getEmployeeid());
        return info;
    }
    //renzheng
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 封装用户的登录数据
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //连接数据库
        User user = userService.queryUsetByName(userToken.getUsername());

        // 没有此人,抛出 UnkownAccountException
        if (user==null){
            return null;
        }
        //获取当前登录的用户对象
        Subject subject = SecurityUtils.getSubject();

        //存放到Session中
        Session session = subject.getSession();
        session.setAttribute("user", user);
        // realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可
        String realmName = getName();
        System.out.println(realmName);

        // 盐值。使用 username作为盐值，盐值必须是唯一的
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getAccount());
        /*三个参数:
            principals：身份，即主体的标识属性，可以是任何东西，如用户名、邮箱等，唯一即可。
            一个主体可以有多个principals，但只有一个Primary principals，一般是用户名/密码/手机号。
            credentials: 传递的密码对象
            realmName: 认证名(指定当前 Realm 的类名)
        */
        // 密码认证, shiro自己做
        // 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo
        return new SimpleAuthenticationInfo(user,user.getPassword(),credentialsSalt,realmName);
    }

}
